/*
* 字典类型模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, verifyToken } = require("../../../config/utils");
// 引入日志
const log = require("../../log");

// 获取所有字典类列表
router.get("/list", async (req, res) => {
    console.log("===========获取字典类列表接口============");
    // 获取参数
    let { pageNum, pageSize, dictCode, dictName, status, params } = req.query;
    // 拼接sql语句
    let sql = "select * from sys_dict_type";
    let sql_where = ` where 1=1`;
    if(dictCode){
        sql_where += ` and dict_code like '%${dictCode}%'`;
    }
    if(dictName){
        sql_where += ` and dict_name like '%${dictName}%'`;
    }
    if(status){
        sql_where += ` and status = '${status}'`;
    }
    if(params){
        sql_where += ` and create_time between '${params['beginTime']}' and  '${params['endTime']}'`;
    }
    if(dictCode || dictName || status || params){
        sql += sql_where;
    }
    
    // 分页
    sql += ` limit ${(pageNum-1)*pageSize}, ${pageSize}`;
    // 查询数据库
    db.query("查询字典类列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询字典类列表失败", data: err});
            return;
        }
        // 查询总数
        db.query("查询字典类总数", `select count(*) as count from sys_dict_type ${sql_where}`, (err, count)=>{
            if(err){
                res.send({code: 500, msg: "查询字典类总数失败", data: err});
                return;
            }
            if(result.length > 0){
                 // 变量Json数组key转成下划线第一个大写
                 result = result.map(item => {
                    return toCamelCase(item)
                })
                res.send({code: 200, msg: "查询字典类列表成功", rows: result, total: count[0].count});
            }else{
                res.send({code: 200, msg: "查询字典类列表成功", rows: [], total: 0});
            }
        })
    })
})

// 新增字典类
router.post("/", (req, res)=>{
    console.log("===========新增字典类接口============");
    // 获取参数
    let {dictName, dictType, status, remark} = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断字典名称和字典类型是否重复
    db.query("查询字典名称和字典类型是否重复", `select * from sys_dict_type where dict_name = '${dictName}' or dict_type = '${dictType}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询字典名称和字典类型是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "字典名称或字典类型已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into sys_dict_type (dict_name, dict_type, status, remark, create_by, create_time)
        values 
        ('${dictName}', '${dictType}', '${status}', ${remark ? "'"+remark+"'" : null}, '${username}', '${createTime}')`;
        db.query("新增字典类", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增字典类失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增字典类成功"});
            }else{
                res.send({code: 500, msg: "新增字典类失败"});
            }
        })
    })
})

// 查询单个字典类
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个字典类接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个字典类", `select * from sys_dict_type where dict_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个字典类失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个字典类成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个字典类失败"});
        }
    })
})

// 修改字典类型
router.put("/", (req, res)=>{
    console.log("===========修改字典类型接口============");
    // 获取参数
    let {dictName, dictType, status, remark, dictId} = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询字典类型名称是否重复
    db.query("查询字典名称和字典类型是否重复", `select * from sys_dict_type where dict_id != ${dictId} and ( dict_name = '${dictName}' or dict_type = '${dictType}' )`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询字典名称和字典类型是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "字典名称或字典类型已存在", data: []});
            return;
        }
        // 修改字典类型sql
        let sql = `update sys_dict_type set dict_name = '${dictName}',  dict_type = '${dictType}', status = '${status}',
        remark=${remark ? "'"+remark+"'" : null}, update_by = '${username}', update_time = '${updateTime}'
        where dict_id = ${dictId}`;
        db.query("修改字典类型", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改字典类型失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改字典类型成功", data: []});
            }else{
                res.send({code: 500, msg: "修改字典类型失败", data: []});
            }
        })
    })
})

// 删除字典类型
router.delete("/:id", (req, res) => {
    console.log("===========删除字典类型接口============");
    // 获取参数
    let {id} = req.params;
     // 拼接sql,删除多条数据
     let sql = `delete from sys_dict_type where dict_id in(${id})`;
    // 查询数据库
    db.query("删除字典类型", sql, (err, result) => {
        if (err) {
            res.send({code: 500, msg: "删除字典类型失败", data: err});
            return
        }
        if(result.affectedRows > 0){
            res.send({code: 200, msg: "删除字典类型成功"})
        }else{
            res.send({code: 500, msg: "删除字典类型失败"})
        }
    })
})

module.exports = router;